<?php
//家庭作业中心
Namespace Api\Controller;
use Think\Controller;
use Api\Model;
class HomeworkApiController extends ApiBaseController {

    //我的课表
    public function mySchedule(){
        $strDate = I("date");
        $strUsername =$this->getDefaultUserName();
        //$strUsername="100466471";
        //$strDate="20180403";
        $strDbDate =    $this->DatetimeToDbFormat($strDate);
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrLesson0 =  $mdlLesson->getOfflineLessonList($strDbDate,$strDbDate,$strUsername);
        $arrLesson = array();
        foreach($arrLesson0 as $row)
        {
            $arrTime = explode("-",$row["content"]);
            if(count($arrTime)<2)continue;
            $arrLesson[] = array(
                "start"=>$arrTime[0],
                "stop" =>$arrTime[1],
                "detail"=>$row["classname"],
                "scheduleId"=>$row["classcode"]
            );
        }
        // c.startDate,c.starttime,c.endtime,b.BookName,c.scheduleId,c.materialId
        /*
         * “start”: “14:00”,
        “stop”: “15:00”,
        “detail”: “”,
        “scheduleId”: 11

         * */
        $arrLessonOnline0 = $mdlLesson->getOnlineLesson($strDbDate,$strDbDate,$strUsername);
        $arrLessonOnline=array();
        foreach($arrLessonOnline0 as $row2)
        {
            $arrLessonOnline[] = array(
                "start"=>date("H:i",strtotime($row2["starttime"])),
                "stop" =>date("H:i",strtotime($row2["endtime"])),
                "detail"=>$row2["bookname"],
                "scheduleId"=>$row2["scheduleid"]
            );
        }
        $arrResult = array(
            "offline"=>$arrLesson,
            "online"=>$arrLessonOnline
        );
        ShowJsonReturnAndDie($arrResult);
    }

    public function deleteUsername(){
        $strToken=I("token");
        $mdlParent =new \Api\Model\AppParentsModel();
        $iParent = $mdlParent->getIdByToken($strToken);
        $strDeleteUsername =I("deleteUsername");
        $db = $mdlParent->getStudentDb();
        $db->where("username='%s' and parentid=%d",$strDeleteUsername,$iParent)->save(array("parentid"=>"0"));
        //die($db->getLastSql());
        // 获取默认用户并更新当前默认用户
        $strNewDefaultUsername = $mdlParent->getDefaultStudentByParentID($iParent);
        $mdlParent->where("id=%d",$iParent)->save(array("defaultchildusername"=>$strNewDefaultUsername));
        ShowJsonReturnAndDie(null);
    }

    //总课表
    public function totalSchedule(){
        $strDBStartDate = DbDateFormat(I("startDate"));
        $strDBEndDate =DbDateFormat(I("endDate"));
        $strUsername =$this->getDefaultUserName();
        //$strDBStartDate="20180328";
        //$strDBEndDate=  "20180405";
        //$strUsername="100466470";
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrLesson0 =  $mdlLesson->getOfflineLessonList($strDBStartDate,$strDBEndDate,$strUsername);
        $arrLesson = array();
        foreach($arrLesson0 as $row)
        {
            $arrTime = explode("-",$row["content"]);
            if(count($arrTime)<2)continue;
            $arrLesson[] = array(
                "date" =>DbDateFormat($row["regtime"]),
                "start"=>$arrTime[0],
                "stop" =>$arrTime[1],
                "detail"=>$row["classname"],
                "scheduleId"=>$row["classcode"],
                "type"=>2
            );
        }

        $arrLessonOnline0 = $mdlLesson->getOnlineLesson($strDBStartDate,$strDBEndDate,$strUsername);
        $arrLessonOnline=array();
        foreach($arrLessonOnline0 as $row2)
        {
            $arrLessonOnline[] = array(
                "date" =>DbDateFormat($row2["endtime"]),
                "start"=>date("H:i",strtotime($row2["starttime"])),
                "stop" =>date("H:i",strtotime($row2["endtime"])),
                "detail"=>$row2["bookname"],
                "scheduleId"=>$row2["scheduleid"],
                "type"=>1
            );
        }
        $arrResult = array(
            "offline"=>$arrLesson,
            "online"=>$arrLessonOnline
        );
        ShowJsonReturnAndDie($arrResult);
    }
    //   public function totalSchedule(){
    //       $strStartDate =I("startDate");
    //       $strEndDate =I("endDate");
    //       $strUsername =$this->getDefaultUserName();
    //       $strStartDate="20180328";
    //       $strEndDate=  "20180405";
    //       $strUsername="100466471";
    //       $mdlLessones =new \Home\Model\AppLessonModel();
    //       $arrResult0 = $mdlLessones->getOfflineLessonList($this->DatetimeToDbFormat($strStartDate),$this->DatetimeToDbFormat($strEndDate),$strUsername);
    //       $arrResult=array();
    //       foreach($arrResult0 as $row)
    //       {
    //           $arrTime = explode("-",$row["content"]);
    //           if(count($arrTime)<2)continue;
    //           $arrResult[] = array(
    //               "date"=>DbDateFormat($row["regtime"]),
    //               "start"=>$arrTime[0],
    //               "stop" =>$arrTime[1],
    //               "detail"=>$row["classname"],
    //               "scheduleId"=>$row["classcode"],
    //               "type"=>2
    //               );
    //       }
    //       $strSql = "select c.startDate,c.starttime,c.endtime,b.BookName,c.scheduleId,c.materialId
    //from APP_ScheduleCache c left join TB_WxReadBook b on b.ID = c.materialId
    //where username='%s' and datediff(d,c.endtime,'%s')<=0 and datediff(d,c.endtime,'%s')>=0 order by c.id desc";
    //       $db = $mdlLessones->getScheduleCacheDb();
    //       $arrResult11 = $db ->query($strSql,$strUsername,$this->DatetimeToDbFormat($strStartDate),$this->DatetimeToDbFormat($strEndDate));
    //       //die($db->getLastSql());
    //       $arrResult2  = array();
    //       foreach($arrResult11 as $row)
    //       {
    //           $arrResult2[] = array(
    //               "date"=>DbDateFormat($row["endtime"]),
    //               "start"=>date("H:i",strtotime($row["starttime"])),
    //               "stop" =>date("H:i",strtotime($row["endtime"])),
    //               "detail"=>$row["bookname"],
    //               "scheduleId"=>$row["scheduleid"],
    //               "type"=>1
    //               );
    //       }


    //       ShowJsonReturnAndDie(array(
    //           "offline"=>$arrResult ,
    //           "online"=>$arrResult2
    //           ));
    //   }
    //编辑课表任务
    public function editSchedule(){
        $iScheduleId=I("scheduleId");
        $iMaterialId=I("materialId");
        $strDate = I("startDate");
        $iTotalDays = I("totalDays");
        $strStart = I("start");
        $strStop  = I("stop");
        $strUsername = $this->getDefaultUserName();
        //$strDBStartDate="20180328";
        //$strDBEndDate=  "20180405";
        //$strUsername="100466470";
        //$strUsername="100466363";
        //$iScheduleId = 80;
        //$iMaterialId=316;
        //$strDate = "20180331";
        //$iTotalDays = rand(1,50);
        //$strStart = "13:00";
        //$strStop  = "16:00";
        //$strUsername="dengchang";
        $strDbDate = $this->DatetimeToDbFormat($strDate);
        $mdlLesson =new \Api\Model\AppLessonModel();
        if(!$mdlLesson->isScheduleRecordExists($iScheduleId))
        {
            ShowJsonReturnAndDie(null,true,"计划已被删除");
        }
        $dbSchedule = $mdlLesson->getScheduleDb();
        $arrReturn = $dbSchedule->where("id=%d and username='%s'",$iScheduleId,$strUsername)->save(array(
            "materialId"=> $iMaterialId ,//教材id
            "startDate"=> $strDbDate ,
            "totalDays"=> $iTotalDays,
            "start"=>$strStart,
            "stop"=>$strStop
        ));
        $mdlLesson->updateScheduleCache($strUsername,$iScheduleId,$strDbDate,$strStart,$strStop,$iTotalDays,$iMaterialId);
        ShowJsonReturnAndDie(null);
    }
    //添加课表任务
    public function addSchedule(){
        /*
         * “materialId”: 11,//教材id
    “startDate”: “20180312”,
    “week”: “1,2,4”,
    “totalDays”: 30,
    “start”: “12:30”,
    “stop”: “13:00
         * */
        $iMaterialId=I("materialId");
        $strDate = I("startDate");

        $iTotalDays = I("totalDays");
        $strStart = I("start");
        $strStop  = I("stop");
        $strUsername = $this->getDefaultUserName();
        //$strUsername="100466470";
        //$iMaterialId=316;
        //$strDate = "20180330";
        //$iTotalDays = 30;
        //$strStart = "09:15";
        //$strStop  = "15:00";
        $strDbDate = $this->DatetimeToDbFormat($strDate);
        $mdlLesson =new \Api\Model\AppLessonModel();
        $dbSchedule = $mdlLesson->getScheduleDb();
        $iReturnID = $dbSchedule->add(array(
            "materialId"=> $iMaterialId ,//教材id
            "startDate"=> $strDbDate ,
            "totalDays"=> $iTotalDays,
            "start"=>$strStart,
            "stop"=>$strStop,
            "status"=>0,
            "username"=>$strUsername
        ));
        //die(json_encode($arrReturn));
        $iID = $iReturnID;
        $mdlLesson->updateScheduleCache($strUsername,$iID,$strDbDate,$strStart,$strStop,$iTotalDays,$iMaterialId);

        $dbSchedule->where("id=%d",$iID)->save(array(
            "status"=>1
        ));
        ShowJsonReturnAndDie(null);
    }

    //获取课表任务
    public function getSchedule(){
        $strUsername = $this->getDefaultUserName();
        $ischeduleId = I("scheduleId");
        //$strUsername="100466471";
        //$ischeduleId= 9;
        $mdlLesson = new \Api\Model\AppLessonModel();
        $arrInfo = $mdlLesson->getScheduleDetail($strUsername,$ischeduleId);
        if($arrInfo==null){
            ShowJsonReturnAndDie(null,true,"此计划不存在");
        }
        ShowJsonReturnAndDie(array(
            "materialId"=> $arrInfo["materialid"],//教材id
            "name"=> $arrInfo["bookname"],//教材，名称
            "imageUrl"=> $mdlLesson->getBookCoverUrl($arrInfo["dirname"]), //教材封面
            "startDate"=>DbDateFormat($arrInfo["startdate"]),
            "totalDays"=> $arrInfo["totaldays"],
            "start"=> date_format(date_create($arrInfo["start"]),"H:i"),
            "stop"=>  date_format(date_create($arrInfo["stop"]),"H:i")
        ));
    }
    //删除课程
    public function deleteSchedule(){
        $strUsername = $this->getDefaultUserName();
        $ischeduleId = I("scheduleId");
        $mdlLesson =new \Api\Model\AppLessonModel();
        $dbSchedule = $mdlLesson->getScheduleDb();
        $dbScheduleCache = $mdlLesson->getScheduleCacheDb();
        $dbScheduleCache->where("username='%s' and scheduleId=%d",$strUsername,$ischeduleId)->delete();
        $dbSchedule->where("username='%s' and id=%d",$strUsername,$ischeduleId)->delete();
        ShowJsonReturnAndDie(null);
    }
    //我的线上课程
    public function myCoursesOnline(){
        $strUsername=$this->getDefaultUserName();
        // $strUsername="dengchang";
        $mdlLesson =new \Api\Model\AppLessonModel();
        // [FinishCnt], [TotalCnt], [materialId], [BookName], [DirName]
        $arrResult0=  $mdlLesson->getCourseOnline($strUsername);
        $arrResult=array();
        foreach($arrResult0 as $row){
            $arrResult[]=array(
                "name"=>$row["bookname"],
                "imageUrl"=>$mdlLesson->getBookCoverUrl($row["dirname"]),
                "progress"=>$row["finishcnt"]."/".$row["totalcnt"]
            );
        }
        ShowJsonReturnAndDie($arrResult);
    }

    //我的线下课程
    public function myCoursesOffline(){
        /*
         * offline”:[//线下课程---年度课
        {
        “name”: “”,//AS1
        “type”: 1, //1:AS1 2:AS2 3:AP0……
        “progress”: “12/120”
        }
        ],
        “holiday”:[//寒暑假课程
        {
        “name”: “”,
        “type”: 1,
        “progress”: “12/120”
        }
        ],
        “activity”:[//活动课程
        {
        “name”: “”,
        “type”: 1,
        “progress”: “12/120”
        }
         * classCode	classname	CourseParentType	timenumber	SurplusNumber
         * 83502	  AS1-Phase 1	年度课	120	112
         */
        $strUsername = $this->getDefaultUserName();
        // $strUsername = "100466057";
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrTypeList = $mdlLesson->getTypeIconMapList();
        $arrResult0 =  $mdlLesson->getCoursesOffline($strUsername);
        $arroffline = array();
        $arrholiday = array();
        $arractivity = array();
        foreach($arrResult0 as $row){
            $strCoverID =$mdlLesson->getClassIconID($arrTypeList,$row["classname"]);
            $strProgress = $row["surplusnumber"]."/".$row["timenumber"];
            if($row["courseparenttype"]=="年度课")
            {
                $arroffline[]=array(
                    "name"=>$row["classname"],
                    "coverid"=>$strCoverID,
                    "progress"=>$strProgress
                );
            }
            if($row["courseparenttype"]=="活动课")
            {
                $arractivity[]=array(
                    "name"=>$row["classname"],
                    "coverid"=>$strCoverID,
                    "progress"=>$strProgress
                );
            }

            if($row["courseparenttype"]=="特训营")
            {
                $arrholiday[]=array(
                    "name"=>$row["classname"],
                    "coverid"=>$strCoverID,
                    "progress"=>$strProgress
                );
            }
        } // end  foreach($arrResult0 as $row){
        $arrResult = array(
            "offline" =>$arroffline,
            "holiday" =>$arrholiday,
            "activity"=>$arractivity
        );
        ShowJsonReturnAndDie($arrResult);
    }

    //随堂作业列表
    public function myClassworks(){
        $strUsername =$this->getDefaultUserName();
        $mdlLessons =new \Api\Model\AppLessonModel();
        $strDate = date("Y-m-d");
        $arrLessones =  $mdlLessons->getOfflineLessonList($strDate,$strDate,$strUsername);
        if(count($arrLessones)<1){
            ShowJsonReturnAndDie(null,true,"今日课表无课，无课后作业");
        }
        /*
         * [ID], [TypeCode], [TypeRequest], [TypeStatus],[ClassworksID],[ClassName]
        [id], [typecode], [typerequest], [typestatus],[classworksid],[classname]
         * * */
        $arrTodayLesson = $arrLessones[0];
        $icoursetableid = $arrTodayLesson["coursetableid"];
        $arrClassType0 =  $mdlLessons->getClassworksType($icoursetableid);
        $arrClassType=array();
        /*“className”: “绘本”,
        “request”: “”,
        “materialList”:[
        {
        “bookName”: “”，
        “bookImageUrl”: “”,
        “bookId”: 12
        }
        ]
        }，

         * */
        foreach($arrClassType0 as $row)
        {
            $iTypeID = $row["id"];
            $arrClassworksDetail0 = $mdlLessons->getClassworkDetailByTypeID($iTypeID,$strUsername);
            $arrClassworksDetail  = array();
            foreach($arrClassworksDetail0 as $rowDetail)
            {
                /*“bookName”: “”，
                “bookImageUrl”: “”,
                “bookId”: 12
                }
                 */
                $arrClassworksDetail[]=array(
                    "bookName"=>$rowDetail["ftitle"],
                    "bookImageUrl"=>$mdlLessons->getClassworkImgUrl($rowDetail["fimg"]),
                    "bookId"=>$rowDetail["fid"]
                );
            }
            $arrClassType[]=array(
                "className"=>$row["classname"],
                "request"=>$row["typerequest"],
                "materialList"=>$arrClassworksDetail
            );
        }
        ShowJsonLoginAndDie($arrClassType);

    }
    //歌曲绘本作业详情
    public function myResourceDetail(){
        $iResourseId = I("resourseId");
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrResult =  $mdlLesson->getResourceDetail($iResourseId);
        /*“imageUrl”: “”,
“resourceUrl”: “”, //播放地址
         * */
        ShowJsonReturnAndDie(array(
            "imageUrl"=>$mdlLesson->getClassworkImgUrl($arrResult["fimg"]),
            "resourceUrl"=>$mdlLesson->getClassworkResourceUrl($arrResult["fcontent"])
        ));
    }
    //上传磨耳朵声音
    public function uploadAudioResource(){
        /*
         * "type”: 0 //0:歌曲 1：绘本
   “resourseId”: 12, //歌曲或绘本id
   “page”: 1 //页数
   “lineId”: 1, //行号
    “file”: //直接对应二进制流
    “score”: 4 //分数（可能传有可能不传）
       */
        $strUesrname = $this->getDefaultUserName();
        $iResourceID = I("resourseId");
        $iPage= I("page");
        $iLineID = I("lineId");
        $iScore = I("score");
        $strTitle=qwTrimStr(I("title"));
        $iDuration=I("duration");
        $mdlRecord =new \Api\Model\AppRecordModel ();
        $strAudioPath =$this->saveUploadFile($mdlRecord->getMoerduoRecordType());
        if($strTitle=="")
        {
            ShowJsonReturnAndDie(null,true,"请输入标题");
        }
        if($iDuration<=0)
        {
            ShowJsonReturnAndDie(null,true,"时长不能为零");
        }
        // [path], [addtime], [username], [status], [wxreadbookid], [pageid], [lineid], [score]
        $db=$mdlRecord->getDb();
        //$arrResult = $db->where("username='%s' and wxreadbookid=%d and pageid=%d and lineid=%d and recordtype='%s'",$strUesrname,$iResourceID,$iPage,$iLineID,$mdlRecord->getMoerduoRecordType())->field("id")->find();
        //if($arrResult==null)
        //{
        $db->add(array(
            "path"=>$strAudioPath,
            "addtime" =>date("Y-m-d"),
            "username" =>$strUesrname,
            "status" =>1,
            "wxreadbookid"=>$iResourceID,
            "pageid"=>$iPage,
            "lineid"=>$iLineID,
            "score"=>$iScore,
            "recordtype"=>$mdlRecord->getMoerduoRecordType(),
            "title"=>$strTitle,
            "duration"=>$iDuration
        ));
        $dbPk =new \Api\Model\AppParentsModel();
        $iNetar = $mdlRecord->getNectarNumWhenRecord();
        $dbPk->addNectar($strUesrname,$iNetar,"录音加花蜜"); //录音时加花蜜
        $dbPk->setPkData($strUesrname,$iResourceID,$iPage,$iLineID,$iScore,$strAudioPath);
        // [id], [username], [wxreadbookid], [pageid], [rowid], [score], [recordurl]

        //}else{
        //    $iID = $arrResult["id"];
        //    $db->where("id=%d",$iID)->save(array(
        //    "path"=>$strAudioPath,
        //    "addtime" =>date("Y-m-d"),
        //    "username" =>$strUesrname,
        //     "status" =>1,
        //     "wxreadbookid"=>$iResourceID,
        //     "pageid"=>$iPage,
        //     "lineid"=>$iLineID,
        //     "score"=>$iScore,
        //     "isscorevalid"=>$iIsvalidScore
        //    ));
        //}
        $strCurrentAudioUrl = $mdlRecord->getRecordUrl($strAudioPath);
        $arrList0 = $db->where("username='%s' and wxreadbookid=%d and pageid=%d",$strUesrname,$iResourceID,$iPage)->field("path,lineid")->order("lineid asc")->select();
        $strUrlList = "";
        foreach($arrList0 as $row)
        {
            if($strUrlList!="")$strUrlList.=",";
            $strUrlList .= $mdlRecord->getRecordUrl($row["path"]);
        }
        ShowJsonReturnAndDie(array(
            "resourceUrl"=>$mdlRecord->getRecordUrl($strAudioPath),
            "pageResourceUrl" =>$strUrlList
        ));
    }
   
    public function getMaterialClass(){
        $strUsername = $this->getDefaultUserName();
        $iType = I("type");
        $mdlLesson =new Model\AppLessonModel();
        $arrList=array();
        switch($iType)
        {
            case 0:              
                $arrList =  $mdlLesson->getMoErDuoByTypeID(0);
                break;
            case 1:
                $arrList =  $mdlLesson->getYueDuByTypeID(0);
                break;
            case 3:
                $arrList =  $mdlLesson->getKouyuByTypeID(0);
                break;
            default:
                ShowJsonReturnAndDie(null,true,"类型不存在");
                break;
                
        }
        ShowJsonReturnAndDie($arrList);
    }
    
    public function getMaterialList(){
        $iType = I("type");
        $iClassID = I("classId");
        $mdlLesson =new Model\AppLessonModel();
        $arrList = array();
        switch($iType){
          case 0:
              $arrList = $mdlLesson->getMoErDuoBooksByTypeID($iClassID);
              break;
          case 1:
              $arrList = $mdlLesson->getYueduBooksByTypeID($iClassID);
              break;
          case 2:
              $arrList = $mdlLesson->getKouyuBooksByTypeID($iClassID);
              break;
          default:
              ShowJsonReturnAndDie(null,true,"类型不存在");
              break;
        }
        ShowJsonReturnAndDie($arrList);
    }
    //上传音频-作业
    //public function uploadAudioResourceOfWork(){
    //    $iResID = I("resourceId");
    //    $mdlRec =new \Api\Model\AppRecordModel();
    //    $strType = $mdlRec->getClassworkType();
    //    $strAudioFilePath = $this->saveUploadFile($strType);
    //    // 未完成不知道作业关系是怎么样的。
    //}
    
    public function myTeachingMaterials(){
        $strUsernmae = I("username");
        $mdlLesson =new Model\AppLessonModel();
        $arrOptionList0 =   $mdlLesson->getOptionalMaterial($strUsernmae);
        $arrOptionList = array();
        /**
         *  “materialId”: 11,
      			“name”: “”,
      			“imageUrl”: “”

         */
        foreach($arrOptionList0 as $row){
            $arrOptionList[] = array(
            "materialId"=>$row["id"],
            "name"=>$row["bookname"],
            "imageUrl"=>$mdlLesson->getBookCoverUrl($row["dirname"])
            );
        }
        return ShowJsonReturnAndDie(array("optional"=>$arrOptionList));
    }
    /**
     * 17、获取所有教材列表
     */
    public function getAllMaterialList(){
        $iType = I("type");
        // $iType = 0;
        $mdlLesson =new Model\AppLessonModel();
        // 0:磨耳朵 1:阅读 2:口语
        switch($iType)
        {
           case 0:
               $arrList = $mdlLesson->getMoErDuoALLSub(0);
               ShowJsonReturnAndDie($arrList);
               break;
           case 1:
               $arrList = $mdlLesson->getYueduAllSub(0);
               ShowJsonReturnAndDie($arrList);
               break;
           case 2:
               $arrList = $mdlLesson->getKouyuALLSub(0);
               ShowJsonReturnAndDie($arrList);
               break;        
           default:
               ShowJsonReturnAndDie(null,true,"未知Type参数");
               break;
        }
    }
}